package org.stephen.backend;

import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.stephen.config.AppConfig;
import org.stephen.mapper.SubListMapper;
import org.stephen.model.SubList;
import org.stephen.util.HttpRequestUtil;

@Component
public class StatService {
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
    private static final HashMap<String, Long> lastAlertTime = new HashMap<>();
    @Autowired
    AppConfig appConfig;
    // 股市上午开盘时间和收盘时间
    private static final LocalTime MORNING_OPEN_TIME = LocalTime.of(9, 30);
    private static final LocalTime MORNING_CLOSE_TIME = LocalTime.of(11, 30);
    // 股市下午开盘时间和收盘时间
    private static final LocalTime AFTERNOON_OPEN_TIME = LocalTime.of(13, 0); // 注意：这里假设下午1点开盘，具体可能因地区而异
    private static final LocalTime AFTERNOON_CLOSE_TIME = LocalTime.of(15, 0); // 注意：这里假设下午3点收盘，股市实际收盘时间可能更晚，如15:30

    // 判断当前时间是否在股市交易时间段内
    private static boolean isWithinMarketHours(LocalTime currentTime) {
        // 上午交易时间段检查
        boolean morning = !currentTime.isBefore(MORNING_OPEN_TIME) && currentTime.isBefore(MORNING_CLOSE_TIME);
        // 下午交易时间段检查（注意：这里假设下午有交易，且时间段为13:00-15:00，具体可能因地区而异）
        boolean afternoon = !currentTime.isBefore(AFTERNOON_OPEN_TIME) && currentTime.isBefore(AFTERNOON_CLOSE_TIME);
        // 返回上午或下午是否在交易时间段内的逻辑或结果
        return morning || afternoon;
    }

    // 判断当前日期是否为周一到周五
    private static boolean isWeekday(DayOfWeek dayOfWeek) {
        return dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
    }
    @Autowired
    SubListMapper subListMapper;

    @Scheduled(fixedRate = 3000)
    public void check() {
        try {
            LocalDateTime currentDateTime = LocalDateTime.now();
            DayOfWeek dayOfWeek = currentDateTime.getDayOfWeek();
            if (!isWeekday(dayOfWeek) || !isWithinMarketHours(LocalTime.now())) {
                return;
            }
            List<SubList> subLists = subListMapper.selectList(new QueryWrapper<>());
            for (SubList subList : subLists) {
                check(subList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void check(SubList subList) {
        try {
            if (!subList.getSubStatus()) {
                return;
            }
            String subCode = subList.getSubCode();
            double value = getLastPrice(subCode);
            System.out.println("检测值" + value);
            double minValue;
            double maxValue;
            try {
                minValue = Double.parseDouble(subList.getSubValue().split(",")[0]);
                maxValue = Double.parseDouble(subList.getSubValue().split(",")[1]);
            } catch (NumberFormatException e) {
                minValue = Double.parseDouble(subList.getSubValue().split("，")[0]);
                maxValue = Double.parseDouble(subList.getSubValue().split("，")[1]);
            }
            if (value >= maxValue || value <= minValue) {
                if (lastAlertTime.get(subList.getOpenid()) == null ||
                        System.currentTimeMillis() - lastAlertTime.get(subList.getOpenid()) >= 30 * 60 * 1000) {
                    lastAlertTime.put(subList.getOpenid(), System.currentTimeMillis());
                    sendSubscribeMessage(subList.getOpenid(), value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private double getLastPrice(String code) throws Exception {
        String urlStr = "https://finance.pae.baidu.com/selfselect/getstockquotation?all=1&code=" + code + "&isIndex=true&isBk=false&isBlock=false&isFutures=false&isStock=false&newFormat=1&market_type=ab&group=quotation_index_fiveday&finClientType=pc";
        String cookie = "BIDUPSID=B6D5BBDC81F5505D0D65CCEA41974975; PSTM=1659529095; BAIDUID=B276EDBCFE50DB1F72638C5A1279978C:FG=1; BAIDUID_BFESS=B276EDBCFE50DB1F72638C5A1279978C:FG=1; H_WISE_SIDS=60975_60942_61027_61025_61035; H_WISE_SIDS_BFESS=60975_60942_61027_61025_61035; PSINO=3; delPer=0; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=60942_61027_61035_61054_61098_60851_61130_61127_61114_61135_61141; BA_HECTOR=0h258gakah0hala5aka185a42g7in81jj44lr1u; ZFY=9diHN3aSO2EfxStk9nF6ATghOrQ9svB45N3d6dRsxFc:C; BCLID=11396152004887007453; BCLID_BFESS=11396152004887007453; BDSFRCVID=YatOJexroG33EzoJ-6lMMB7XQAY06Y5TDYLEOwXPsp3LGJLVYKiVEG0Ptoe2l_P-oxIJogKK0eOTHkAF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BDSFRCVID_BFESS=YatOJexroG33EzoJ-6lMMB7XQAY06Y5TDYLEOwXPsp3LGJLVYKiVEG0Ptoe2l_P-oxIJogKK0eOTHkAF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tRk8oIL2fIvbfP0k-J32h-QH-UnLetJXfKcy5h7F54nKDp0R3PvvMxTDXhJDWxDfyN6LahkMLUjxsMT4QqD254KY5hb0-qQAQDn32-3N3KJmfh-6DROYLDue2bb32-biWbR-2Mbd2hjP_IoG2Mn8M4bb3qOpBtQmJeTxoUJ25DnJhhCGe6LbejjXeHAs2C6ebIO2B5rM2RrJHJuk-PnVePI7qtnZKRvHa2keoh5LahFVM45-XfKbWh_FWH0qX6Qn3N5rKCKK5qK5epjyKp6m3lFUMJj405OTbIO-oJR7LT6oJhT_hPJvyT88XnO7aMolXbrtXp7_2J0WStbKy4oTjxL1Db3JKjvMtgDtVDD5fC_KbDPr-R-_-4_tbh_X5-RLfK3D5h7F54nKDp0RDU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1.0.1_MzA0OTFjMzcxMTZlMWM0MTJmNDYwM2M5YzU0NzRmYmIzM2FkNDkxYzQzNTM3NjI3MDljYzBkOWYzOTRhMGU1YmUxZTVkN2U2ZmE1NzYxYzQ5YTQ5ZThjMTgyOTkxMjdhNTIwZDQ4MjNmZmI5MzYxYmNlNzI0ZDJlYmNmNDBiNTI5ODRmYzk2NDM0NWJiOTFmOTM4YmIxYjM5MmUzYjNhMg==";
        String token = "1731319520996_1731335202069_BM7EDspF6r0Bx1MXdbEcl7jqMHbgYAeK02rmHbt5mYW64uFq41RYxNK96oJbcCWMOR+PckLS1y2wFaVei9k4uhJqHBs6DI+u1dlEOJbJuecMcJO1599CpwQu2ep2DWWX88S175bp2ySPCFXAAxAiud1Sql6jmp9eGT1KTd+jQ2TwPbABMkFSSuCpyMBulCenGZU9ks+612K66ThLmpuxDfJsqSGREla9PEjm2xk9sR+fQvND+TFlmf54Ce7i9R6bV6L9YDHK3zT+6SQZZZ4Pnot8zXcv7hZNjR0HCXp6UkjunvuM3Qb3i+ks7EoOaSmrxE0L2/DOo8BSqwaXXEsTu9OxKcnyL+EfhXVKRHSUj5BSXYauQjqMaoayb9NwjQwEd4iFx/O2wQHcK/mh1NuePw==";
        JSONObject item;
        try {
            String response = HttpRequestUtil.doGet(urlStr, cookie, token);
            JSONObject object = JSONObject.parseObject(response).getJSONObject("Result");
            JSONArray fivedays = object.getJSONArray("fivedays");
            JSONObject jsonObject = fivedays.getJSONObject(fivedays.size() - 1);
            JSONArray priceinfos = jsonObject.getJSONArray("priceinfos");
            item = priceinfos.getJSONObject(priceinfos.size() - 1);
        } catch (Exception e) {
            urlStr = "https://gushitong.baidu.com/opendata?query=159919&resource_id=5803&finClientType=pc";
            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
            String response = HttpRequestUtil.doGet(urlStr, null, null);
            return JSONObject.parseObject(response)
                    .getJSONArray("Result").getJSONObject(0)
                    .getJSONObject("DisplayData")
                    .getJSONObject("resultData")
                    .getJSONObject("tplData")
                    .getJSONObject("result").getJSONArray("newest").getJSONObject(1).getDouble("value");
        }
        return item.getDouble("price");
    }


    // 获取 Access Token
    public String getAccessToken() throws IOException {
        String url = TOKEN_URL + "?grant_type=client_credential&appid=" + appConfig.getAppid() + "&secret=" + appConfig.getSecret();
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(request)) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("access_token")) {
                    return json.getString("access_token");
                } else {
                    System.out.println("Failed to get access token: " + result);
                    return null;
                }
            }
        }
    }

    public void sendSubscribeMessage(String openId, Double value) throws IOException {
        String accessToken = getAccessToken();
        String url = MESSAGE_URL + "?access_token=" + accessToken;
        // 构建消息主体
        JSONObject message = new JSONObject();
        message.put("touser", openId); // 用户的OpenID
        message.put("template_id", "agzzVsacu1Zcm9YM42UnK4pYfYvd6oJ6UyJF8jnCYnc"); // 模板ID
        message.put("page", "pages/k/index"); // 跳转页面
        message.put("miniprogram_state", "formal"); // 正式版
        message.put("lang", "zh_CN"); // 简体中文
        // 构建消息内容
        JSONObject data = new JSONObject();
        // 通知类型
        JSONObject thing1 = new JSONObject();
        thing1.put("value", "检测到目标值"); // 示例通知类型
        data.put("thing1", thing1);
        // 消息条数
        JSONObject thing2 = new JSONObject();
        thing2.put("value", "1"); // 示例消息条数
        data.put("thing2", thing2);
        // 消息来自
        JSONObject thing3 = new JSONObject();
        thing3.put("value", value); // 示例消息来源
        data.put("thing3", thing3);
        // 将数据添加到消息主体
        message.put("data", data);
        // 发送 HTTP POST 请求
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json");
            post.setEntity(new StringEntity(message.toString(), "UTF-8")); // 设置为UTF-8编码
            try (CloseableHttpResponse response = client.execute(post)) {
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("Message Send Response: " + result);
            }
        }
    }
}